package com.nantong.admin.config;

import cn.dev33.satoken.stp.StpInterface;
import com.nantong.admin.service.ISysPermissionService;
import com.nantong.admin.service.ISysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Sa-Token 权限认证实现
 *
 * @author nantong
 */
@Component
@RequiredArgsConstructor
public class SaTokenPermissionConfig implements StpInterface {

    private final ISysRoleService roleService;
    private final ISysPermissionService permissionService;

    /**
     * 获取权限列表
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 将用户ID从loginId中提取（格式为 "userType:userId"）
        String[] parts = loginId.toString().split(":");
        if (parts.length != 2) {
            return new ArrayList<>();
        }
        
        Long userId = Long.parseLong(parts[1]);
        Set<String> permissionKeys = permissionService.listPermissionKeysByUserId(userId);
        return new ArrayList<>(permissionKeys);
    }

    /**
     * 获取角色列表
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 将用户ID从loginId中提取（格式为 "userType:userId"）
        String[] parts = loginId.toString().split(":");
        if (parts.length != 2) {
            return new ArrayList<>();
        }
        
        Long userId = Long.parseLong(parts[1]);
        Set<String> roleKeys = roleService.selectRoleKeysByUserId(userId);
        return new ArrayList<>(roleKeys);
    }
}
